package jp.sinya.clientsystem.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public abstract class BaseServlet extends HttpServlet {

    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String methodName = req.getParameter("method");
        if (null == methodName || methodName.trim().isEmpty()) {
            throw new RuntimeException("没有传递方法名");
        }

        Class clazz = this.getClass();//得到当前HttpServlet类的class类对象,目的是调用自身的getMethod方法
        Method method = null;
        try {
            //解释:调用本类中的一个名叫method的方法，参数是后面的那两个
            method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
        } catch (Exception e) {
            throw new RuntimeException("调用的方法" + methodName + "不存在");
        }

        //反射调用
        try {
            //this.addUser(req,res), method(this, req, res);
            String result = (String) method.invoke(this, req, res);
            if (result == null || result.trim().isEmpty()) {
                return;
            }

            if (result.contains(":")) {
                int index = result.indexOf(":");
                String type = result.substring(0, index);//截取前半部分
                String path = result.substring(index + 1);//截取后半部分
                if (type.equalsIgnoreCase("redirect")) {
                    res.sendRedirect(req.getContextPath() + path);
                } else if (type.equalsIgnoreCase("forward")) {
                    req.getRequestDispatcher(path).forward(req, res);
                } else {
                    throw new RuntimeException("无法实现类型： " + type + " 的操作");
                }

            } else {
                //没有:标识，默认result就是转发的路径
                req.getRequestDispatcher(result).forward(req, res);
            }

        } catch (Exception e) {
            throw new RuntimeException("调用的方法 " + methodName + "(HttpServletRequest req, HttpServletResponse res) 内部出现异常:" + e.toString());
        }
    }

}
